/**********************************************
** @Des: This file ...
** @Author: xiaomeng79
** @Date:   17-11-20 下午6:07
***********************************************/
package models

import (
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/validation"
	"errors"
)

type Privilege struct {
	Id int
	Pri_name string
	Controller_name string
	Action_name string
	Par_path string
	Created_at int64
	Updated_at int64
	Is_usable int
}

/**
设置表名称
 */
func (a *Privilege) TableName() string {
	return "rbac_privilege"
}

/**
增加
 */
func (a *Privilege) Add() (int64, error) {
	if err := a.valid("add");err != nil {
		return -1,err
	}
	return orm.NewOrm().Insert(a)
}

/**
列表
 */
func (a *Privilege) Lst() ([]Privilege) {
	var Privileges []Privilege
	//获取querybuild对象
	qb,_ := orm.NewQueryBuilder("mysql")
	//构建查询对象
	qb.Select("id","pri_name","controller_name","action_name","CONCAT(par_path,'-',id) as par_path","created_at").
		From(a.TableName()).
		Where("is_usable = 1").
		OrderBy("par_path").Asc()
	//导出sql
		sql := qb.String()
	//执行Sql
		o := orm.NewOrm()
		o.Raw(sql).QueryRows(&Privileges)
	return Privileges

}

/**
获取对象用ID
 */
func GetPrivilegeById(id int) (*Privilege, error) {
	r := new(Privilege)
	err := orm.NewOrm().QueryTable(r.TableName()).Filter("id",id).Filter("is_usable",1).One(r)
	if err != nil {
		return nil, errors.New("信息错误")
	}
	return r, nil
}

/**
修改
 */
func (a *Privilege) Edit(fields ...string) (error) {
	if _, err := orm.NewOrm().Update(a, fields...); err != nil {
		return err
	}
	return nil
}



/**
数据验证
 */
func (a *Privilege) valid(str string) (error) {
	v := validation.Validation{}

	//公共的
	if res := v.Required(a.Pri_name, "权限名称"); !res.Ok {
		return errors.New(res.Error.Key+res.Error.Message)
	}
	if res := v.Required(a.Controller_name, "控制器名称"); !res.Ok {
		return errors.New(res.Error.Key+res.Error.Message)
	}
	if res := v.Required(a.Action_name, "方法名称"); !res.Ok {
		return errors.New(res.Error.Key+res.Error.Message)
	}
	if res := v.Required(a.Par_path, "父级路径"); !res.Ok {
		return errors.New(res.Error.Key+res.Error.Message)
	}

	//add需要验证的
	if str == "add" {

	}

	return nil

}

